package com.zby.business.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.zby.business.R;
import com.zby.business.activity.Detail;
import com.zby.business.net.MyAsyncTask;
import com.zby.business.util.App;
import com.zby.business.util.Util;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

/**
 * Created by BY on 2015/12/29.
 */
public class ShoppingCarFragment extends Fragment {
    private View view;
    private ListView carListView;
    private LinearLayout emptyLayout;
    private App app;
    private ArrayList commodityDetailId, commodityName, commodityPrice, commodityPicture, commodityIntroduce, commoditySale;
    private ArrayList time, number, cartId;
    private CartListViewAdapter adapter;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.gouwuche, null);
        initView();
        checkCar();
        adapter = new CartListViewAdapter();
        carListView.setAdapter(adapter);
        return view;
    }

    private void initView() {
        commodityDetailId = new ArrayList();
        commodityName = new ArrayList();
        commodityPrice = new ArrayList();
        commodityPicture = new ArrayList();
        commodityIntroduce = new ArrayList();
        commoditySale = new ArrayList();
        time = new ArrayList();
        cartId = new ArrayList();
        number = new ArrayList();
        app = (App) getActivity().getApplication();
        carListView = (ListView) view.findViewById(R.id.carListView);
        emptyLayout = (LinearLayout) view.findViewById(R.id.gouwucheEmpty);
    }

    @Override
    public void onResume() {
        checkCar();
        adapter.notifyDataSetChanged();
        super.onResume();
    }

    private void checkCar() {
        MyAsyncTask asyncTask = new MyAsyncTask();
        try {
            String s = asyncTask.execute("phoneShoppingCar?userId=" + app.getUserId()).get();
            System.out.println(s);
            JSONObject object = new JSONObject(s);
            JSONArray details = object.getJSONArray("detail");
            JSONArray carts = object.getJSONArray("cart");
            clearData();
            for (int i = 0; i < carts.length(); i++) {
                JSONObject commodity = (JSONObject) details.get(i);
                JSONObject cart = (JSONObject) carts.get(i);
                commodityDetailId.add(commodity.get("commodityDetailId"));
                commodityName.add(commodity.get("commodityBrand"));
                commodityPrice.add(commodity.get("commodityPrice"));
                commodityPicture.add(commodity.get("commodityPicture"));
                commodityIntroduce.add(commodity.get("commodityIntroduce"));
                commoditySale.add(commodity.get("commoditySale"));
                time.add(cart.get("time"));
                number.add(cart.get("number"));
                cartId.add(cart.get("cartid"));
            }
            if (carts.length() > 0) {
                emptyLayout.setVisibility(View.GONE);
                carListView.setVisibility(View.VISIBLE);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void clearData() {
        commodityDetailId.clear();
        commodityName.clear();
        commodityPrice.clear();
        commodityPicture.clear();
        commodityIntroduce.clear();
        commoditySale.clear();
        time.clear();
        number.clear();
    }

    private void purchase(final int position) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View view = inflater.inflate(R.layout.confirm, null);
        final AlertDialog alert = new AlertDialog.Builder(getContext(), AlertDialog.THEME_HOLO_LIGHT).create();
        final Button subButton = (Button) view.findViewById(R.id.subButton);
        Button addButton = (Button) view.findViewById(R.id.addButton);
        Button cofirmButton = (Button) view.findViewById(R.id.cofirmButton);
        final EditText numberEditText = (EditText) view.findViewById(R.id.numberEditText);
        final int[] number1 = {Integer.parseInt(numberEditText.getText().toString())};
        subButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number1[0] = Integer.parseInt(numberEditText.getText().toString());
                numberEditText.setText(number1[0] - 1 + "");
                if (number1[0] == 2) {
                    subButton.setClickable(false);
                }
            }
        });
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number1[0] = Integer.parseInt(numberEditText.getText().toString());
                numberEditText.setText(number1[0] + 1 + "");
                if (number1[0] > 1) {
                    subButton.setClickable(true);
                }
            }
        });
        cofirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyAsyncTask asyncTask = new MyAsyncTask();
                MyAsyncTask asyncTask1 = new MyAsyncTask();
                try {
                    asyncTask.execute("deleteFromCart?userId=" + app.getUserId() + "&detailId=" + commodityDetailId.get(position) + "&cartId=" + cartId.get(position)).get();
                    String s = asyncTask1.execute("phonePurchase?detailId=" + commodityDetailId.get(position) + "&userId=" + app.getUserId() + "&price=" + Float.parseFloat(commodityPrice.get(position) + "") * Integer.parseInt(numberEditText.getText().toString()) + "&number=" + numberEditText.getText().toString()).get();
                    if (s.equals("success")) {
                        Util.toast(getContext(), "操作成功");
                        commodityDetailId.remove(position);
                        commodityPrice.remove(position);
                        commodityPicture.remove(position);
                        commodityName.remove(position);
                        cartId.remove(position);
                        commoditySale.remove(position);
                        commodityIntroduce.remove(position);
                        time.remove(position);
                        number.remove(position);
                        if (commodityDetailId.size() < 1) {
                            carListView.setVisibility(View.GONE);
                            emptyLayout.setVisibility(View.VISIBLE);
                        }
                        adapter.notifyDataSetChanged();
                    } else {
                        Util.toast(getContext(), "出问题了");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Util.toast(getContext(), "出问题了");
                }
                alert.dismiss();
            }
        });
        alert.setView(view);
        alert.show();
    }

    class CartListViewAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private ImageLoader imageLoader;
        private LruCache cache;

        public CartListViewAdapter() {
            inflater = LayoutInflater.from(getContext());
            cache = new LruCache((int) (Runtime.getRuntime().maxMemory() / 20));
            imageLoader = ImageLoader.getInstance();
            ImageLoaderConfiguration config = ImageLoaderConfiguration.createDefault(getContext());
            imageLoader.init(config);
        }

        @Override
        public int getCount() {
            return commodityDetailId.size();
        }

        @Override
        public Object getItem(int position) {
            return commodityDetailId.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.cart_list_view, null);
            final String[] urls = commodityPicture.get(position).toString().split("\\;");
            final ImageView carImage = (ImageView) view.findViewById(R.id.carListViewImage);
            TextView carIntroduce = (TextView) view.findViewById(R.id.carIntroduceTextView);
            TextView carprice = (TextView) view.findViewById(R.id.carPriceText);
            Button carCancel = (Button) view.findViewById(R.id.carCancelButton);
            Button carPay = (Button) view.findViewById(R.id.carPayButton);


            Bitmap bitmap = (Bitmap) cache.get(urls[0]);
            if (bitmap != null) {
                carImage.setImageBitmap(bitmap);
            } else {
                imageLoader.displayImage(Util.BASE_URL + urls[0], carImage);
                imageLoader.loadImage(Util.BASE_URL + urls[0], new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String s, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String s, View view, FailReason failReason) {

                    }

                    @Override
                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                        cache.put(urls[0], bitmap);
                    }

                    @Override
                    public void onLoadingCancelled(String s, View view) {

                    }
                });
            }


            carIntroduce.setText(commodityName.get(position) + "");
            carprice.setText("￥" + commodityPrice.get(position));
            carCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyAsyncTask asyncTask = new MyAsyncTask();
                    try {
                        String s = asyncTask.execute("deleteFromCart?userId=" + app.getUserId() + "&detailId=" + commodityDetailId.get(position) + "&cartId=" + cartId.get(position)).get();

                        if (s.equals("success")) {
                            commodityDetailId.remove(position);
                            commodityPrice.remove(position);
                            commodityPicture.remove(position);
                            commodityName.remove(position);
                            cartId.remove(position);
                            commoditySale.remove(position);
                            commodityIntroduce.remove(position);
                            time.remove(position);
                            number.remove(position);
                            if (commodityDetailId.size() < 1) {
                                carListView.setVisibility(View.GONE);
                                emptyLayout.setVisibility(View.VISIBLE);
                            }
                            adapter.notifyDataSetChanged();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            carPay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        purchase(position);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), Detail.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("introduce", commodityIntroduce.get(position) + "");
                    bundle.putString("price", commodityPrice.get(position) + "");
                    bundle.putString("sale", commoditySale.get(position) + "");
                    bundle.putString("commodityId", commodityDetailId.get(position) + "");
                    bundle.putString("url", commodityPicture.get(position) + "");
                    intent.putExtra("bundle", bundle);
                    startActivity(intent);
                }
            });
            return view;
        }
    }

}
